package com.yourenbang.lingyun.transaction.job.handler;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.yourenbang.lingyun.core.util.DingdingUtils;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.domain.FundAccount;
import com.yourenbang.lingyun.transaction.config.DingdingConfig;
import com.yourenbang.lingyun.transaction.job.model.dto.AccountAlarmDTO;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundAccountMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

//TODO 需要重新测试
@Component
@Slf4j
public class FundAccountHandler {

    @Autowired
    private TransactionFundAccountMapper transactionFundAccountMapper;
    @Autowired
    private DingdingConfig dingdingConfig;


    @XxlJob("accountAlarm")
    public ReturnT<String> accountAlarm(String param) throws Exception {
        XxlJobLogger.log("【账户余额查询】任务开始。。。入参:" + param);
        Map<Integer, BigDecimal> dto = null;
        AccountAlarmDTO accountAlarmDTO = new AccountAlarmDTO();
        if (StringUtils.isNotBlank(param)) {
            accountAlarmDTO = JSON.parseObject(param, AccountAlarmDTO.class);
        }
        dto = accountAlarmDTO.getAlarmAmount();

        List<FundAccount> sysAccounts = transactionFundAccountMapper.getAllSysAccount(accountAlarmDTO.getPlatNo());

        for (FundAccount sysAccount : sysAccounts) {
            BigDecimal alarmAmount = null;
            if (dto != null) {
                alarmAmount = dto.get(sysAccount.getAccountType());
            }
            if (alarmAmount == null) {
                alarmAmount = new BigDecimal("100000");
            }
            if (sysAccount.getAccountAmountWithdrawable().compareTo(alarmAmount) < 0) {
                StringBuilder dingMark = new StringBuilder("【账户余额不足预警】");
                dingMark.append(sysAccount.getAccountName() + "仅剩["
                        + sysAccount.getAccountAmountWithdrawable() + "],请尽快充值!");
                DingdingUtils.sendToDingding(dingMark.toString(), dingdingConfig.getDingdingWarnToken());
            }
        }

        return ReturnT.SUCCESS;
    }

}
